package gowcage.mvp.presenter;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;

import gowcage.mvp.model.IModel;
import gowcage.mvp.model.Model;
import gowcage.mvp.view.IView;

/**
 * Created by Administrator on 2017/4/8.
 * Presenter 处理业务逻辑
 */

public class Presenter implements IPresenter {

    //Model和View各自实现了他们自己的接口，而Presenter只需要持有他们的接口
    IView iView;
    IModel iModel;
    Handler handler;

    public Presenter(IView iView) {//在View中创建Presenter实例，传入View中实现的iView实例
        this.iView = iView;//将传入的iView赋值给此类的全局iView
        initModel();
        handler = new Handler(Looper.getMainLooper());//要刷新主线程的UI，在子线程中实例要带上参数（Looper.getMainLooper()）；
    }

    private void initModel() {//获取数据，此处仅测试，实际视情况而定
        iModel = new Model("mvp", "123");
    }

    @Override
    public void clear() {//清除，调用iView的onClearText()方法
        iView.onClearText();
    }

    @Override
    public void doLogin(String name, String passwd) {//执行登录

        Boolean isLoginSuccess = true;
        final int code = iModel.checkUserValidity(name, passwd);//检查用户名密码正确性
        if (code != 0) isLoginSuccess = false;//如果返回值不为0，则账号密码不正确
        final Boolean result = isLoginSuccess;
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                iView.onLoginResult(result, code);
            }
        }, 2000);//延时2秒，模拟耗时操作

    }

    @Override
    public void setProgressBarVisiblity(int visiblity) {//设置进度条可见
        iView.onSetProgressBarVisibility(visiblity);
    }
}
